package com.cts.tmall.app.controller;

import com.cts.tmall.biz.service.FileService;
import com.cts.tmall.com.exception.SystemException;
import com.cts.tmall.com.message.RspCode;
import com.cts.tmall.dal.entity.TmallFile;
import com.google.common.collect.ImmutableMap;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/file")
public class FileController {

    @Autowired
    private FileService fileService;

    @PostMapping
    public Map<String, Object> upload(MultipartFile file) {
        TmallFile dbFile = fileService.upload(file.getOriginalFilename(), file.getContentType());

        try {
            File localFile = new File(dbFile.getFilePath(), dbFile.getFileId().toString());
            localFile.getParentFile().mkdirs();
            file.transferTo(localFile);
        } catch (Exception e) {
            log.error("文件上传失败！", e);
            throw new SystemException(RspCode.FAILURE_SYSTEM, "文件上传失败！");
        }

        return ImmutableMap.<String, Object>builder()
                .put("fileId", dbFile.getFileId())
                .put("fileName", dbFile.getFileName())
                .build();
    }

    @GetMapping("/{fileId}")
    public ResponseEntity<byte[]> download(@PathVariable("fileId") Integer fileId) throws IOException {
        TmallFile dbFile = fileService.download(fileId);
        File localFile = new File(dbFile.getFilePath(), dbFile.getFileId().toString());
        if (!localFile.exists()) {
            log.error("文件下载失败！本地文件不存在！");
            throw new SystemException(RspCode.FAILURE_SYSTEM, "文件不存在！");
        }
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", dbFile.getFileType());
        return new ResponseEntity<byte[]>(FileCopyUtils.copyToByteArray(localFile), headers, HttpStatus.OK);
    }

}
